package com.software.loginregister;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.software.loginregister.activity.ForgetPasswordActivity;
import com.software.loginregister.activity.TasteSelectionActivity;
import com.software.loginregister.api.UserApi;
import com.software.loginregister.activity.RegisterActivity;
import com.software.loginregister.entity.Result;
import com.software.loginregister.entity.User;
import com.software.loginregister.util.RetrofitClient;
import com.software.loginregister.util.SharedPreferencesUtil;

import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class LoginActivity extends AppCompatActivity {
    private EditText edtUsername, edtPassword;
    private Button btnLogin;
    private CheckBox checkboxRemember;
    private UserApi userApi;
    private TextView tvRegister;
    private TextView tvForgetPassword;
    private ImageView ivPasswordVisibility;
    private boolean isPasswordVisible = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // 设置状态栏
        setStatusBar();
        // 初始化视图
        edtUsername = findViewById(R.id.edt_username);
        edtPassword = findViewById(R.id.edt_password);
        checkboxRemember = findViewById(R.id.checkbox_remember);
        btnLogin = findViewById(R.id.btn_login);
        tvRegister = findViewById(R.id.tv_register);
        tvForgetPassword = findViewById(R.id.tv_forget_password);

        // 获取API实例
        userApi = RetrofitClient.getInstance().create(UserApi.class);

        // 检查是否记住密码
        if (SharedPreferencesUtil.isRemembered(this)) {
            edtUsername.setText(SharedPreferencesUtil.getUsername(this));
            edtPassword.setText(SharedPreferencesUtil.getPassword(this));
            checkboxRemember.setChecked(true);
        }
        // 获取从注册页面传来的用户名
        String username = getIntent().getStringExtra("username");
        if (username != null && !username.isEmpty()) {
            edtUsername.setText(username);
            edtPassword.requestFocus(); // 自动将焦点设置到密码输入框
        }
        // 登录按钮点击事件
        btnLogin.setOnClickListener(v -> performLogin());
        //注册按钮点击事件
        tvRegister.setOnClickListener(v -> {
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            startActivity(intent);
        });
        // 忘记密码按钮点击事件
        tvForgetPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到忘记密码页面
                Intent intent = new Intent(LoginActivity.this, ForgetPasswordActivity.class);
                startActivity(intent);
            }
        });
    }

    private void setStatusBar() {
        Window window = getWindow();
        // 设置状态栏背景为透明
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);

        // 设置状态栏文字颜色为深色
        View decorView = window.getDecorView();
        int flags = decorView.getSystemUiVisibility();
        flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        decorView.setSystemUiVisibility(flags);

    }

    private void performLogin() {
        String username = edtUsername.getText().toString().trim();
        String password = edtPassword.getText().toString().trim();
        boolean isRemember = checkboxRemember.isChecked();

        if (username.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show();
            return;
        }

        Map<String, String> loginForm = new HashMap<>();
        loginForm.put("username", username);
        loginForm.put("password", password);

        userApi.login(loginForm).enqueue(new Callback<Result<User>>() {
            @Override
            public void onResponse(Call<Result<User>> call, Response<Result<User>> response) {
                try {
                    Log.d("LoginDebug", "服务器响应状态码: " + response.code());
                    if (response.isSuccessful() && response.body() != null) {
                        Result<User> result = response.body();
                        Log.d("LoginDebug", "登录响应结果: " + (result != null ? "成功" : "为空"));
                        Log.d("LoginDebug", "响应码: " + (result != null ? result.getCode() : "null"));

                        if (result.getCode() == 200 || (result.getCode() == 1 && result.getData() != null)) {
                            User user = result.getData();
                            Log.d("LoginDebug", "获取到的用户信息: " + (user != null ? "不为空" : "为空"));

                            if (user != null && user.getUserId() != null) {
                                Long userId = user.getUserId();
                                Log.d("LoginDebug", "获取到的用户ID: " + userId);

                                // 保存登录状态和用户信息
                                SharedPreferencesUtil.saveLoginStatus(
                                        LoginActivity.this,
                                        isRemember,
                                        username,
                                        password,
                                        userId
                                );
                                Log.d("LoginDebug", "已保存登录状态到 SharedPreferencesUtil");

                                // 保存用户头像URL
                                String avatarUrl = user.getAvatar();
                                Log.d("LoginDebug", "用户头像URL: " + avatarUrl);
                                // 额外保存用户ID到user_info
                                SharedPreferences.Editor editor = getSharedPreferences("user_info", MODE_PRIVATE).edit();
                                editor.putLong("userId", userId);
                                editor.putString("username", username);
                                editor.putString("avatar_url", avatarUrl);  // 添加这行，保存头像URL
                                editor.apply();
                                Log.d("LoginDebug", "已保存用户信息到 user_info SharedPreferences");

                                // 同时使用工具类保存
                                SharedPreferencesUtil.saveUserAvatar(LoginActivity.this, avatarUrl);
                                Log.d("LoginDebug", "已保存用户信息到 SharedPreferences");
                                // 验证保存后的userId
                                Long savedUserId = SharedPreferencesUtil.getUserId(LoginActivity.this);
                                Log.d("LoginDebug", "验证保存的用户ID: " + savedUserId);


                                runOnUiThread(() -> {
                                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent(LoginActivity.this, TasteSelectionActivity.class);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                    intent.putExtra("userId", userId);
                                    intent.putExtra("userName", user.getUserName());
                                    startActivity(intent);
                                    finish();
                                });
                            } else {
                                runOnUiThread(() -> {
                                    Toast.makeText(LoginActivity.this, "登录失败：用户信息不完整", Toast.LENGTH_SHORT).show();
                                });
                            }
                        } else {
                            String errorMsg = result.getMsg();
                            runOnUiThread(() -> {
                                Toast.makeText(LoginActivity.this,
                                        errorMsg != null ? errorMsg : "登录失败",
                                        Toast.LENGTH_SHORT).show();
                            });
                        }
                    } else {
                        runOnUiThread(() -> {
                            Toast.makeText(LoginActivity.this,
                                    "登录失败: " + response.message(),
                                    Toast.LENGTH_SHORT).show();
                        });
                    }
                } catch (Exception e) {
                    Log.e("LoginDebug", "处理响应时出错", e);
                    runOnUiThread(() -> {
                        Toast.makeText(LoginActivity.this,
                                "登录处理出错: " + e.getMessage(),
                                Toast.LENGTH_SHORT).show();
                    });
                }
            }

            @Override
            public void onFailure(Call<Result<User>> call, Throwable t) {
                Log.e("LoginDebug", "网络请求失败", t);
                runOnUiThread(() -> {
                    Toast.makeText(LoginActivity.this,
                            "网络错误: " + t.getMessage(),
                            Toast.LENGTH_LONG).show();
                });
            }
        });
    }
}